//index.js
//获取应用实例
var Bmob = require("../../utils/bmob.js");
var app = getApp();
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var wxApi = require('../../es6-promise/utils/wxApi.js')
var wxRequest = require('../../es6-promise/utils/wxRequest.js')
Page({
  data: {
    postsList: [],
    postsShowSwiperList: [],
    isLastPage: false,
    page: 1,
    search: '',
    categories: 0,
    showerror: "none",
    showCategoryName: "",
    categoryName: "",
    showallDisplay: "block",
    displayHeader: "none",
    displaySwiper: "none",
    floatDisplay: "none",
    topBannerHeight: Math.ceil(290.0 / 750.0 * getApp().screenWidth),
    middlerBannerHeight: Math.ceil(190.0 / 750.0 * getApp().screenWidth),
    banner: [],
    shortMenus: [{
      src: "../../images/xcx.png",
      id: "xcx",
      typeCode: "xcx",
      typeId:'224',
      typeName: "小程序"
    }, {
      src: "../../images/wzjs.png",
      id: "wzjs",
      typeCode: "wzjs",
      typeId: '10',
      typeName: "网站建设"
    }, {
      src: "../../images/ggsj.png",
      id: "ggsj",
      typeCode: "ggsj",
      typeId: '226',
      typeName: "广告设计"
    }, {
      src: "../../images/wsc.png",
      id: "wsc",
      typeCode: "wsc",
      typeId: '71',
      typeName: "微商城"
    }]
  },
  //搜索内容提交
  formSubmit: function (e) {
    var url = '../list/list'
    if (e.detail.value.input != '') {
      url = url + '?search=' + e.detail.value.input;
      wx.navigateTo({
        url: url
      })
    }else {
      wx.showModal({
        title: '提示',
        content: '请输入搜索内容',
        showCancel: false,
      });
    }
  },
  onPullDownRefresh: function () {
    var self = this;
    self.setData({
      showerror: "none",
      showallDisplay: "none",
      displaySwiper: "none",
      floatDisplay: "none",
      isLastPage: false,
      page: 0,
      postsShowSwiperList: []
    });
    this.fetchTopFivePosts();

  },
  onReachBottom: function () {
    //console.log("xialajiazai");  
  },
  onShow: function (options) {
    wx.setStorageSync('openLinkCount', 0);
  },  
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  loadBanner: function () {
    var me = this;
    var Banner = Bmob.Object.extend("Banner");
    var query = new Bmob.Query(Banner);
    query.equalTo("position", "index_top");//查询首页顶部的广告栏
    query.equalTo("data_state", 0);//默认查询启用的数据
    query.select("image", "imageSrc");//只要返回图片信息
    query.find({
      success: function (results) {
        var banner = [];
        for (var i = 0; i < results.length; i++) {
          banner.push(results[i].get("imageSrc") ? results[i].get("imageSrc") : results[i].get("image")._url);
        }
        me.setData({
          banner: banner
        });
        wx.setStorageSync("indexTopBanner", banner);
      },
      error: function (e) {
        console.error(e, "find_error")
      }
    });

  },
  onLoad: function () {
    var me = this;
    /*var banner = wx.getStorageSync("indexTopBanner");
    if (!banner || banner.length === 0) {
      me.loadBanner();
    } else {
      me.setData({
        banner: banner
      });
    }*/
    let sysParam = wx.getStorageSync("sysParam");
    if (!sysParam) {
      me.loadSysParam();
    } else {
      me.setData({
        intro: sysParam.SYS_INTRO,
        address: sysParam.SYS_ADDRESS,
        detailAddress: sysParam.SYS_ADDRESS,
        mobile: sysParam.SYS_MOBILE,
        mobile2: sysParam.SYS_MOBILE2,
        latitude: parseFloat(sysParam.SYS_ADDRESS_LATITUDE),
        longitude: parseFloat(sysParam.SYS_ADDRESS_LONGITUDE),
        fax: sysParam.SYS_FAX,
        title: sysParam.SYS_TITLE,
        markers: [{
          iconPath: "/images/map.png",
          latitude: parseFloat(sysParam.SYS_ADDRESS_LATITUDE),
          longitude: parseFloat(sysParam.SYS_ADDRESS_LONGITUDE),
          //title: sysParam.SYS_TITLE,
          callout: {
            content: sysParam.SYS_TITLE,
            padding: 20,
            fontSize: 16,
            color: '#1296db',
            bgColor: '#F5FFFA',
            borderRadius: 8,
            display: 'ALWAYS'
          }
        }]
      });
    }
    //加载文章
    var topFivePosts = wx.getStorageSync("topFivePosts");
    if (!topFivePosts || topFivePosts.length == 0){
      me.fetchTopFivePosts();
    }else{
      me.setData({
        postsShowSwiperList: me.data.postsShowSwiperList.concat(topFivePosts.map(function (item) {
          //item.firstImage = Api.getContentFirstImage(item.content.rendered);
          item.post_medium_image_300 = item.post_thumbnail_image;
          if (item.post_medium_image_300 == null || item.post_medium_image_300 == '') {
            if (item.content_first_image != null && item.content_first_image != '') {
              item.post_medium_image_300 = item.content_first_image;
            }
            else {
              item.post_medium_image_300 = Api.getContentFirstImage(item.content.rendered);
            }

          }
          return item;
        })),
        showallDisplay: "block",
        displaySwiper: "block"
      });
      me.fetchPostsData(me.data);
    }
  },
  fetchTopFivePosts: function () {
    var self = this;
    //取置顶的文章
    var getPostsRequest = wxRequest.getRequest(Api.getStickyPosts());
    getPostsRequest.then(response => {
      if (response.data.length > 0) {
        wx.setStorageSync("topFivePosts", response.data);
        self.setData({
          postsShowSwiperList: self.data.postsShowSwiperList.concat(response.data.map(function (item) {
            //item.firstImage = Api.getContentFirstImage(item.content.rendered);
            item.post_medium_image_300 = item.post_thumbnail_image;
            if (item.post_medium_image_300 == null || item.post_medium_image_300 == '') {
              if (item.content_first_image != null && item.content_first_image != '') {
                item.post_medium_image_300 = item.content_first_image;
              }
              else {
                item.post_medium_image_300 = Api.getContentFirstImage(item.content.rendered);
              }

            }
            return item;
          })),
          showallDisplay: "block",
          displaySwiper: "block"
        });

      } else {
        self.setData({
          displaySwiper: "none",
          displayHeader: "block",
          showallDisplay: "block"
        });
      }
    }).then(response => {
      self.fetchPostsData(self.data);

    }).catch(function () {
      self.setData({
        showerror: "block",
        floatDisplay: "none"
      });

    }).finally(function () {
      // console.log(response); 

    });

  },
  //获取文章列表数据
  fetchPostsData: function (data) {
    var self = this;
    if (!data) data = {};
    if (!data.page) data.page = 1;
    if (!data.categories) data.categories = 0;
    if (!data.search) data.search = '';
    if (data.page === 1) {
      self.setData({
        postsList: []
      });
    };
    wx.showLoading({
      title: '正在加载',
      mask: true
    });
    var getPostsRequest = wxRequest.getRequest(Api.getPosts(data));
    getPostsRequest
      .then(response => {
        if (response.statusCode === 200) {

          if (response.data.length < 6) {
            self.setData({
              isLastPage: true
            });
          }
          self.setData({
            floatDisplay: "block",
            postsList: self.data.postsList.concat(response.data.map(function (item) {

              var strdate = item.date
              if (item.category_name != null) {

                item.categoryImage = "../../images/category.png";
              }
              else {
                item.categoryImage = "";
              }

              if (item.post_thumbnail_image == null || item.post_thumbnail_image == '') {
                item.post_thumbnail_image = Api.getContentFirstImage(item.content.rendered);
              }
              item.date = util.cutstr(strdate, 10, 1);
              return item;
            })),

          });
          setTimeout(function () {
            wx.hideLoading();
          }, 900);
        }
        else {
          if (response.data.code == "rest_post_invalid_page_number") {
            self.setData({
              isLastPage: true
            });
            wx.showToast({
              title: '没有更多内容',
              mask: false,
              duration: 1500
            });
          }
          else {
            wx.showToast({
              title: response.data.message,
              duration: 1500
            })
          }
        }


      })
      .catch(function (response) {
        if (data.page == 1) {

          self.setData({
            showerror: "block",
            floatDisplay: "none"
          });

        }
        else {
          wx.showModal({
            title: '加载失败',
            content: '加载数据失败,请重试.',
            showCancel: false,
          });
          self.setData({
            page: data.page - 1
          });
        }

      })
      .finally(function (response) {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      });
  },
  //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      //console.log('当前页' + self.data.page);
      this.fetchPostsData(self.data);
    }
    else {
      wx.showToast({
        title: '没有更多内容',
        mask: false,
        duration: 1000
      });
    }
  },
  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    wx.navigateTo({
      url: url
    })
  },
  //返回首页
  redictHome: function (e) {
    //console.log('查看某类别下的文章');  
    var id = e.currentTarget.dataset.id,
      url = '/pages/index/index';
    wx.switchTab({
      url: url
    });
  },
  //菜单点击事件
  menuClick: function (e) {
    console.log(e);
    let params = e.currentTarget.dataset, typeCode = params.typeCode, typeName = params.typeName, typeId = params.typeId;
    wx.reLaunch({
      url: "../case/case?typeCode=" + typeCode + "&typeName=" + typeName + "&typeId=" + typeId,
      fail: function (e) {
        console.log(e, "error")
      }
    });
  },
  //打开地图
  openLocation: function () {
    var me = this;
    wx.openLocation({
      address: me.data.detailAddress,
      name: me.data.title,
      latitude: parseFloat(me.data.latitude),
      longitude: parseFloat(me.data.longitude),
      success: function () {
      },
      fail: function () {
      },
      complete: function () {
      }
    });
  },
  //拨打电话
  makePhoneCall: function (e) {
    var me = this;
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.number
    });
  },
  //加载系统参数
  loadSysParam: function () {
    var me = this;
    var SysParam = Bmob.Object.extend("SysParam");
    var query = new Bmob.Query(SysParam);
    query.containedIn("code", ['SYS_INTRO', "SYS_ADDRESS", "SYS_MOBILE", "SYS_MOBILE2", "SYS_FAX", "SYS_ADDRESS_LATITUDE", "SYS_ADDRESS_LONGITUDE", "SYS_TITLE"]);
    query.find({
      success: function (results) {
        var sysParam = wx.getStorageSync("sysParam") || {};
        for (var i = 0; i < results.length; i++) {
          var code = results[i].get("code");
          var value = results[i].get("value");
          sysParam[code] = value;
        }
        me.setData({
          intro: sysParam.SYS_INTRO,
          address: sysParam.SYS_ADDRESS,
          detailAddress: sysParam.SYS_ADDRESS,
          mobile: sysParam.SYS_MOBILE,
          mobile2: sysParam.SYS_MOBILE2,
          latitude: parseFloat(sysParam.SYS_ADDRESS_LATITUDE),
          longitude: parseFloat(sysParam.SYS_ADDRESS_LONGITUDE),
          title: sysParam.SYS_TITLE,
          markers: [{
            iconPath: "/images/map.png",
            latitude: parseFloat(sysParam.SYS_ADDRESS_LATITUDE),
            longitude: parseFloat(sysParam.SYS_ADDRESS_LONGITUDE),
            //title: sysParam.SYS_TITLE,
            callout: {
              content: sysParam.SYS_TITLE,
              padding: 20,
              fontSize: 16,
              color: '#1296db',
              bgColor: '#F5FFFA',
              borderRadius: 8,
              display: 'ALWAYS'
            }
          }]
        });
      },
      error: function (error) {
        console.log(error, "error");
      }
    });
  },
  //设置转发分享
  onShareAppMessage: function () {
    return {
      title: '“凡象科技”网站微信小程序.技术支持：www.fansiom.com',
      path: 'pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})
